package com.bds.btcdc.adapter.okex.trade;

import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.adapter.huobi.trade.util.HttpUtilProxy;
import com.bds.btcdc.http.MD5Util;
import com.bds.btcdc.adapter.zb.service.ZBTradeService;
import com.bds.btcdc.util.Const;
import com.bds.btcdc.util.EhcacheUtils;
import com.bds.btcdc.util.HttpUtilManager;
import org.apache.http.HttpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by DongChenchen on 2018/5/9 0008
 */
public class OkexAPIClient {
    private static final Logger logger = LoggerFactory.getLogger(ZBTradeService.class);
    private static final String MARKET_API="https://www.okex.com/api/v1/ticker.do?symbol=";
    private String accessKey;
    private String secretKey;
    private final String USERINFO_URL = "/api/v1/userinfo.do?";//获取用户信息URL
    private final String MAKE_ORDER_API = "/api/v1/trade.do";//下单
    private final String URL_PREX = "https://www.okex.com";
    private static ConcurrentMap<Long, OkexAPIClient> userAccess=new ConcurrentHashMap<>();
    private static OkexAPIClient client = null;
    private DecimalFormat df = new DecimalFormat(Const.END_WITH_COUNT);

    public static OkexAPIClient getInstatnce(){
        if(client==null)
            client=new OkexAPIClient();
        return client;
    }

    public static OkexAPIClient getInstance(Long user_id, String accessKey, String secretKey) {
        if(!userAccess.containsKey(user_id)) {
            client=new OkexAPIClient(accessKey,secretKey);
            userAccess.put(user_id,client);
            return client;
        }else{
            return userAccess.get(user_id);
        }
    }
    private OkexAPIClient() {
    }
    private OkexAPIClient(String accessKey, String secretKey) {
        this.accessKey=accessKey;
        this.secretKey=secretKey;
    }

    /**
     * 获取用户信息
     * 访问频率 6次/2秒
     * @return
     * # Response
            {
                "info": {
                    "funds": {
                        "free": { //账户余额
                            "btc": "0",
                            "usd": "0",
                            "ltc": "0",
                            "eth": "0"
                        },
                        "freezed": {//账户冻结余额
                            "btc": "0",
                            "usd": "0",
                            "ltc": "0",
                            "eth": "0"
                        },
                    }
                }
            }
     */
    public String getAccountInfo() {
        // 构造参数签名
        Map<String, String> params = new HashMap<String, String>();
        params.put("api_key", accessKey);
        String sign = MD5Util.buildMysignV1(params, this.secretKey);
        params.put("sign", sign);
        // 发送post请求
        HttpUtilManager httpUtil = HttpUtilManager.getInstance();
        try {
            String s = httpUtil.requestHttpPost(URL_PREX, this.USERINFO_URL, params);
            return s;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getAccountInfoLocal() {
        // 构造参数签名
        Map<String, String> params = new HashMap<String, String>();
        params.put("api_key", accessKey);
        String sign = MD5Util.buildMysignV1(params, this.secretKey);
        params.put("sign", sign);
        // 发送post请求
        HttpUtilProxy httpUtil = HttpUtilProxy.getInstance();
        try {
            String s = httpUtil.requestHttpPost(URL_PREX+USERINFO_URL, params,Const.LOCAL);
            return s;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 根据币对获取最新价格
     * @return
     */
    public String getPriceBySymbol(String symbol){

        HttpUtilProxy httpUtil = HttpUtilProxy.getInstance();
        String json = null;
        try {
            json = httpUtil.get(MARKET_API+symbol, null, Const.LOCAL);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (json == null)
            return null;

        JSONObject object = JSONObject.parseObject(json);
        JSONObject ticker=object.getJSONObject("ticker");
        String last = df.format(ticker.getBigDecimal("last"));
        //usdt 币对的最新交易价格存到缓存（资产情况统计时 使用）
        EhcacheUtils.getInstance().putCache(Const.OKEX.EXCHANGE + "#" + symbol, last);
        return last;
    }

    public String makeOrder(String symbol, String type, Double price, Double amount) {
        // 构造参数签名
        Map<String, String> params = new HashMap<String, String>();
        params.put("api_key", accessKey);
        params.put("symbol",symbol);
        params.put("type",type);
        params.put("price",String.valueOf(price));
        params.put("amount",String.valueOf(amount));
        String sign = MD5Util.buildMysignV1(params, this.secretKey);
        params.put("sign", sign);

        // 发送post请求
        HttpUtilManager httpUtil = HttpUtilManager.getInstance();
        try {
            String s = httpUtil.requestHttpPostLocal(URL_PREX, this.MAKE_ORDER_API, params,Const.LOCAL);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
